package com.umpay.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
import com.umpay.factory.RSACertFactory;

/**
 * 字段加解密
 * 
 * @ClassName FieldSecurity
 * @Description TODO
 * @author FENG JUN LIU
 * @Date 2018年1月29日
 * @version 1.0.0
 */
public class CipherUtil {

    public static String encrypt(String s) throws Exception {
        Key publicKey = RSACertFactory.getUmfPublicKey();
        Cipher cipher = Cipher.getInstance(KeyFactory.getInstance("RSA").getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        String str = new String(Base64.encode(cipher.doFinal(s.getBytes("UTF-8")))).replace("\n", "");
        return str;
    }

    public static String decrypt(String merId, String data) throws Exception {
        PrivateKey pk = RSACertFactory.getPk(merId);
        byte[] b = Base64.decode(data.getBytes("UTF-8"));
        byte[] retB = decryptByPrivateKey(pk, b);
        String retData = new String(retB);
        return retData;
    }

    private static byte[] decryptByPrivateKey(PrivateKey pk, byte[] data) throws Exception {
        byte[] keyBytes = pk.getEncoded();

        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, privateKey);
        return cipher.doFinal(data);
    }
}
